package com.ruoyi.framework.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步线程
 */
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    /**
     * 核心线程数
     */
    @Value("${spring.async.executor.thread.corePoolSize}")
    private int corePoolSize;

    /**
     * 最大线程数
     */
    @Value("${spring.async.executor.thread.maxPoolSize}")
    private int maxPoolSize;

    /**
     * 队列最大长度
     */
    @Value("${spring.async.executor.thread.queueCapacity}")
    private int queueCapacity;

    /**
     * 线程池维护线程所允许的空闲时间
     */
    @Value("${spring.async.executor.thread.keepAliveSeconds}")
    private int keepAliveSeconds;

    /**
     * 线程池对拒绝任务(无线程可用)的处理策略
     */
    private final ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();

    @Bean(name = "asyncTaskExecutor")
    public ThreadPoolTaskExecutor asyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("线程:ASYNC-THREAD-");// 线程名称前缀
        executor.setRejectedExecutionHandler(callerRunsPolicy);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.initialize();
        return executor;
    }

    // 获得线程池
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        taskExecutor.initialize();
        return AsyncConfigurer.super.getAsyncExecutor();
    }

    // 处理异步线程中发生的异常
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        System.out.println("线程异常");
        return AsyncConfigurer.super.getAsyncUncaughtExceptionHandler();
    }
}
